<template>
	<view class="flex-column page">
		<custom-navigation title="商品分类" :rightImg="!isDrag && !selectMode ?addIcon:null" :rightTxt="isDrag?'保存':null"
			@rightAction="saveSort"></custom-navigation>
		<view class="sort-page-tips" v-if="isDrag">
			<u-icon name="error-circle-fill"></u-icon>长按并上下拖动，即可排序
		</view>
		<mxj-draggableTree @sortFinished="sortFinished" v-model="list" :max-deep="2" :item-height="60"
			:item-padding-left="20" shadow-color="#eee" :isDrag="isDrag">
			<view slot-scope={row,$index} class="menu-row" @tap="isDrag ? sortFinished : false">
				<view class="node-item" :style="{'padding-left':(row._level+1) * 16 + 'px'}"   @click="onIcon(row,'select')">
					<view  :class="!row.parent_no ? 'node-item-title root-title':'node-item-title'"  @click.stop="row._children_show = !row._children_show">
						{{row.name}}
						<image style="height:30rpx;width:30rpx;" :src="row._children_show ? downIcon:upIcon" v-if="row.children.length > 0 && !isDrag && row._level <1"></image>
					</view>
					<image v-if="!isDrag && row.classify_name !=='临时分类'"  @click="onIcon(row,'edit')" :src="rightIcon" style="right:0;height: 30rpx;width:30rpx;margin-right: 20rpx;"></image>
					<view  v-if="isDrag" class="drag-content" :data-id="row.HMDrag_id">
						<view class="drag-icon" :style="{'height': 100+'rpx','width':'100rpx','text-align':'center','padding':'35rpx'}">			
							<image  :src="sortIcon" style="height: 30rpx;width:30rpx;"></image>
						</view>
					</view>
				</view>
			</view>
		</mxj-draggableTree>
		<view class="bottom flex-row-center" v-if="isMultiple" @click="multipleSelect">
			<view class="text">已选{{getAllNum()}}</view>
			<view class="btn2">确认选择</view>
		</view>
		<view class="bottom flex-column-center" v-if="!isDrag && !selectMode" @click="isDrag=true">
			<view class="btn">排序</view>
		</view>
	</view>
 
</template>

<script>
	
	import clone from '@/common/api/clone.js'
	export default {
		data() {
			return {
				classifycations: [],
				listHeight: 0,
				list: [],
				isDrag: false,
				selectMode: false,
				isMultiple: false,
				moveList: [],
				dragList:[],
				oldList:[],
				showDrag:true,
				remoteDatas:[],
				addIcon:require("@/static/add.png"),
				upIcon:require("@/static/arrow-up.png"),
				downIcon:require("@/static/arrow-bottom.png"),
				rightIcon:require("@/static/arrow_black.png"),
				sortIcon:require("@/static/sort.png")
			}
		},
		onLoad(options) {
			this.selectMode = options.selectMode ?? false
			this.isMultiple = options.isMultiple ?? false
		},
		onShow(){
			this.getClassifycations();
		},
		computed:{
			listRun:function(){
				let list = clone(this.list)
				return list
			},
			updateNodes:function(){
				let oldList = clone(this.remoteDatas)
				let newList = clone(this.dragList)
				// console.log('updateNodes',newList,oldList)
				let updateList = []
				for(let newIndex in newList){
					for(let nodeIndex in oldList){
						if(newList[newIndex].no == oldList[nodeIndex].no && (oldList[nodeIndex].serial_no != newList[newIndex].serial_no || oldList[nodeIndex].parent_no !=newList[newIndex].parent_no)){
							// console.log("发现修改数据",newList[newIndex].classify_name,oldList[nodeIndex].classify_name,oldList[nodeIndex].serial_no,newList[newIndex].serial_no,oldList[nodeIndex].parent_no,newList[newIndex].parent_no,"-id-",oldList[nodeIndex].id,newList[newIndex].id)
							let req = {
								"serviceName": "srvretail_goods_classify_update",
								"condition": [
									{
										"colName": "id",
										"ruleType": "eq",
										"value": newList[newIndex].id
									}
								],
								"data": [
									{
										"serial_no": Number(newList[newIndex].serial_no),
										"parent_no": newList[newIndex].parent_no,
										"classify_name": newList[newIndex].classify_name,
									}
								]
							}
							updateList.push(clone(req))
						}
					}
				}
				// console.log('req.datas:',updateList)
				return updateList
			}
		},
		methods: {
			onIcon(row,type){
				if(row&&row.classify_name == '临时分类'){
					return;
				}
				console.log(row,type)
				this.onclick({row,type})
			},
			sortFinished: function(id, pid, list) {
				let keys = list || []
				let datas = clone(this.dragList)
				let nodes = []
				for(let id of list){
					for(let data of datas){
						if(id == ''+ data.id){ 
							nodes.push(data)
						}
					}
				}
				console.log(id,pid,list,nodes)
				this.updateTreeNodes(id,nodes,pid)
			},
			
			updateTreeNodes(moveid,nodes,pid){
				let seqs = nodes.map(item => Number(item.serial_no))
				seqs.sort((a,b)=> a - b)
				let ids = nodes.map(item => item.id)
				let datas = clone(this.dragList)
				let parentNos = nodes.map(item => item.parent_no)
				if(nodes.length != 1){
					parentNos =  [...new Set(parentNos)]
					for(let node of datas){
						if(node.id == moveid){
							let oldpid = node.parent_no
							for(let pNo of parentNos){
								if(oldpid !== pNo){
									node.parent_no = pNo
								}
							}
						}
						for(let idIndex in ids){
							if(node.id == Number(ids[idIndex]) &&  Number(node.serial_no) !== Number(seqs[idIndex])){
								// console.log(node.classify_name,'::',seqs[idIndex],node.serial_no)
								node.serial_no = Number(seqs[idIndex])
							}else{
								node.serial_no = Number(node.serial_no)
							}
						}
					}
				}else{
					parentNos = clone(datas.filter(item => item.id == pid))
					for(let node of datas){
						if(node.id == moveid){
							node.parent_no = parentNos[0].no
						}
					}
				}
				
				this.dragList = clone(datas.map(item => item).sort((a,b) => a.serial_no - b.serial_no))
				this.getClassifycations(this.dragList)
				// console.log(seqs,ids,nodes,clone(this.dragList))
				
			},
			getAllNum() {
				console.log("getAllNum");
				let count = 0;
				for (let i in this.moveList) {
					if (this.moveList[i].check) {
						count++
					}
				}
				return count;
			},
			multipleSelect() {
				let list = [];
				for (let i in this.moveList) {
					if (this.moveList[i].check) {
						list.push(this.moveList[i])
					}
				}
				uni.setStorageSync("multipleSelectClassify", list)
				uni.navigateBack()
			},
			saveSort() {
				uni.showLoading({
					title: "加载中..."
				})
				if (this.isDrag == false) {
					uni.navigateTo({
						url: '/pages/goods/baseinfo/add_goods_classfiy'
					})
				} else {
					this.isDrag = false;
					
					let params = [];
					let count=0;
					for (let i in this.moveList) {
						if (this.moveList[i].children != null && this.moveList[i].children.length > 0) {
							for (let j in this.moveList[i].children) { 
								params.push({
									"serviceName": "srvretail_goods_classify_update",
									"condition": [{
										"colName": "id",
										"ruleType": "eq",
										"value": this.moveList[i].children[j].id
									}],
									"data": [{
										"serial_no": count,
										"parent_no":this.moveList[i].no
									}]
								})
								count++
							}
						}else{
							params.push({
								"serviceName": "srvretail_goods_classify_update",
								"condition": [{
									"colName": "id",
									"ruleType": "eq",
									"value": this.moveList[i].id
								}],
								"data": [{
									"serial_no": count
								}]
							})
							count++
						}
					}
					params = this.updateNodes
					if(params.length != 0){
						this.$apiPost("/retail/operate/srvretail_goods_classify_update", params).then(res => {
							uni.hideLoading()
							if (res.state == 'SUCCESS') {
								uni.showToast({
									title: "修改成功！",
									mask: true
								})
								this.getClassifycations()
							}
						})
					}else{
						this.getClassifycations()
					}
					
				}
			},
			getClassifycations(draglist) {
				uni.showLoading({
					title: "加载中..."
				})
				let self = this
				if(!draglist){
					this.$apiPost("/retail/select/srvretail_goods_classify_select", {
						serviceName: "srvretail_goods_classify_select",
						"colNames": ["*"]
					}).then(res => {
						let list = [];
						for (let i in res.data) {
							let item = res.data[i];
							item['_show'] = true
							
							if (item.parent_no == null) { //顶级菜单
								let children = this.getCcChildren(res.data, item.no);
								// item.serial_no = i //保证序列号是从上到下
								item.children = children //用来恢复折叠
								item.name = item.classify_name
								// 设置节点层级 
								item['_children_show'] = true
								item.expand = true
								list.push(item)
								// list.push(...children)
							}
						}
						self.remoteDatas = clone(res.data)
						self.classifycations = list;
						self.dragList = clone(res.data)
						self.$nextTick(()=>{
							self.list = list.map(item => item);
							uni.hideLoading()
						})
					})
				}else{
					let list = [];
					for (let i in draglist) {
						let item = draglist[i];
						item['_show'] = true
						if (item.parent_no == null) { //顶级菜单
							let children = []
							children = clone(this.getCcChildren(draglist, item.no)).map(item=>item)
							item.serial_no = i //保证序列号是从上到下
							item.children = children //用来恢复折叠
							item.name = item.classify_name
							item.expand = true
							list.push(item)
							// list.push(...children)
						}
					}
					// self.oldList = clone(draglist.map(item => item)) 					
					self.classifycations = list;
					
					self.$nextTick(()=>{
						if(!this.isDrag){
							self.list = list.map(item => item);
						}
						
					})
					// this.oldList = clone(list)
					// self.listHeight = this.list.length * 120;
				}
				uni.hideLoading()
				
			},

			getCcChildren(classifycations, parent_no) {
				var list = [];
				for (var i in classifycations) {
					if (classifycations[i].parent_no == parent_no) {
						classifycations[i].serial_no = i //保证序列号是从上到下
						classifycations[i].name = classifycations[i].classify_name
							// 设置节点层级 
							// 处理更深层子节点
							let children = [];
							// children = clone(this.getCcChildren(classifycations, classifycations[i].no)).map(item=>item)
						classifycations[i]['children'] = children
						classifycations[i]['_children_show'] = classifycations[i].hasOwnProperty('_children_show') ?  classifycations[i]['_children_show'] : true
							classifycations[i].expand = true
						list.push(classifycations[i])
						// list.push(...children)
					}
					
				}
				return list;
			},
			onclick(e) {
				// console.log('=== onclick start ===');
				// console.log("被点击行: " + JSON.stringify(e.value));
				// console.log("被点击下标: " + JSON.stringify(e.index));
				// console.log('=== onclick end ===');
				let item = e.row
				let parentData = null;
				let parentNode = clone(this.remoteDatas.filter(item => item.no == e.row.parent_no && e.row.parent_no)).length == 0 ? null : clone(this.remoteDatas.filter(item => item.no == e.row.parent_no && e.row.parent_no))
				
				parentData = parentNode ? JSON.stringify({
							classify_name: parentNode[0].classify_name,
							no: parentNode[0].no,
							parent_no: parentNode[0].parent_no
						}) : null
				
				switch (e.type){
					case 'edit':
						uni.navigateTo({
							url: `/pages/goods/baseinfo/add_goods_classfiy?isEdit=true&isParent=false&parentData=${parentData}&name=${item.classify_name}&currentNo=${item.no}&id=${item.id}`
						})
						break;
					case 'expand':
						let list = clone(this.dragList)
						list = list.map((item,index) =>{
							if(item.no == e.row.no){
								item._children_show = !e.row._children_show 
								item.expand = !e.row.expand
								console.log('expand item._children_show',item,item._children_show)
							}
							if(item.no != e.row.no && (item.path.indexOf(e.row.no) !== -1) && (index+1 > e.index)){
								// 当前节点的所有子节点 同时 切换显示隐藏
								console.log('expand children',index+1,item)
								item._show = !e.row._children_show
							}else{
								item._show = true
							}
							return item
						})
					    console.log('expand',e.row,list)
						this.getClassifycations(list)
						break;
					
					case 'select':
						if(!this.isDrag){
							uni.navigateTo({
								url: `/pages/goods/baseinfo/add_goods_classfiy?isEdit=true&isParent=false&parentData=${parentData}&name=${item.classify_name}&currentNo=${item.no}&id=${item.id}`
							})
						}
						
						break;
					default:
						break;
				}
				
			}
			
		},
		watch:{
			"isDrag":function(nVal,oVal){
				uni.showLoading({
					title:"加载中"
				})
				this.showDrag = false
				console.log(nVal)
				setTimeout(()=>{
					this.showDrag = true
					uni.hideLoading()
				},100)
			}
		}
	}
</script>

<style scoped lang="scss">
	.page {
		height: 100vh;
		width: 100%;
	}
	.menu-row {
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eee;
		height: 100%;
		background-color:#fff;
	}
	.sort-page-tips{
		font-size: 1.15rem;
		padding-left: 20rpx;
		line-height: 80rpx;
		color:rgba(56, 192, 158, 1);
		background-color: rgba(245, 245, 247, 1);
		// transition: transform 0.2s;
		// -webkit-transition: transform 0.2s;
	}
	.node-item{
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}
	.node-item-title{
		display: flex;
		align-items: center;
		color:rgba(102, 102, 102, 1);
			font-weight: 300;
		&.root-title{
			color:rgba(0, 0, 0, 1);
			font-weight: 540;
		}
	}
	.list {
		flex: 1;
		height: 500rpx;
	}

	.bottom {
		width: 100%;
		height: 146rpx;
		justify-content: center;
		opacity: 1;
		background: rgba(255, 255, 255, 1);
		box-shadow: 0 -32rpx 32rpx 3rpx rgba(245, 245, 247, 1);
		z-index: 1;
		.text {
			flex: 1;
			font-size: 32rpx;
			font-weight: 700;
			margin-left: 24rpx;
			color: rgba(51, 51, 51, 1);
		}

		.btn2 {
			width: 320rpx;
			height: 80rpx;
			opacity: 1;
			margin-right: 100rpx;
			border-radius: 40px;
			background: rgba(56, 192, 158, 1);
			font-size: 32rpx;
			font-weight: 700;
			line-height: 80rpx;
			text-align: center;
			color: rgba(255, 255, 255, 1);
		}

		.btn {
			width: 320rpx;
			height: 80rpx;
			opacity: 1;
			border-radius: 40px;
			background: rgba(56, 192, 158, 1);
			font-size: 32rpx;
			font-weight: 700;
			line-height: 80rpx;
			text-align: center;
			color: rgba(255, 255, 255, 1);
		}
	}
</style>
